// 新闻数据管理服务
class NewsStore {
  constructor() {
    this.news = [];
    this.listeners = [];
    this.isLoading = false;
    
    // 初始化时从localStorage加载数据
    this.loadFromStorage();
  }

  // 添加监听器
  addListener(callback) {
    if (typeof callback === 'function' && !this.listeners.includes(callback)) {
      this.listeners.push(callback);
    }
  }

  // 移除监听器
  removeListener(callback) {
    const index = this.listeners.indexOf(callback);
    if (index !== -1) {
      this.listeners.splice(index, 1);
    }
  }

  // 通知所有监听器
  notifyListeners() {
    this.listeners.forEach(callback => callback());
  }

  // 保存数据到localStorage
  saveToStorage() {
    localStorage.setItem('newsData', JSON.stringify(this.news));
  }

  // 从localStorage加载数据
  loadFromStorage() {
    try {
      const storedNews = localStorage.getItem('newsData');
      if (storedNews) {
        this.news = JSON.parse(storedNews);
      } else {
        // 如果没有存储的数据，使用默认数据
        this.news = [
          {
            id: 1,
            title: '公司推出全新工业级无人机系列',
            content: '快飞者科技今日正式发布全新一代工业级无人机系列，该系列产品配备了高清摄像头和智能避障系统，适用于测绘、巡检等多种工业场景。这一系列无人机采用了最新的电池技术，续航时间提升30%，为行业用户提供更高效的解决方案。',
            bottomContent: '本系列产品将于下月正式上市，欢迎广大客户咨询订购。',
            bottomImages: ['https://via.placeholder.com/150/24f355/FFFFFF?text=Product+Detail'],
            publishDate: '2023-11-15T10:30:00',
            status: 'published',
            importantLevel: 'high',
            publisher: 'admin',
            images: ['https://via.placeholder.com/150/24f355', 'https://via.placeholder.com/150/24f355/000000?text=Industrial+Drone']
          },
          {
            id: 2,
            title: '穿越机大赛即将在深圳举办',
            content: '由快飞者科技赞助的全国无人机穿越机大赛将于下月在深圳举行，预计将有超过500名选手参加。本次大赛设置了多个组别，包括专业组、业余组和青少年组，旨在推动无人机运动的普及和发展。',
            bottomContent: '报名通道已开启，欢迎所有无人机爱好者参与。',
            bottomImages: [],
            publishDate: '2023-11-10T14:20:15',
            status: 'published',
            importantLevel: 'medium',
            publisher: 'editor',
            images: ['https://via.placeholder.com/150/24f355', 'https://via.placeholder.com/150/24f355/000000?text=Race+Event']
          },
          {
            id: 3,
            title: '2024年新产品规划公告',
            content: '快飞者科技计划在2024年推出多款创新产品，包括超轻量固定翼无人机和AI辅助飞行控制器。这些新产品将进一步拓展公司在消费级和专业级无人机市场的份额。',
            bottomContent: '我们将持续创新，为客户提供更优质的产品和服务。',
            bottomImages: ['https://via.placeholder.com/150/24f355/FFFFFF?text=2024+Preview'],
            publishDate: '2023-11-05T09:15:30',
            status: 'published',
            importantLevel: 'medium',
            publisher: 'admin',
            images: ['https://via.placeholder.com/150/24f355']
          },
          {
            id: 4,
            title: '无人机安全飞行指南',
            content: '为了保障飞行安全和公共利益，快飞者科技特别推出无人机安全飞行指南，详细介绍了飞行前检查、飞行注意事项和应急处理方法。希望所有用户都能遵守相关规定，安全飞行。',
            bottomContent: '',
            bottomImages: ['https://via.placeholder.com/150/24f355/000000?text=Safety+Tips'],
            publishDate: '2023-10-28T16:45:10',
            status: 'draft',
            importantLevel: 'low',
            publisher: 'editor',
            images: ['https://via.placeholder.com/150/24f355/000000?text=Safety+Guide']
          },
          {
            id: 5,
            title: '公司与高校建立无人机研发合作',
            content: '快飞者科技与深圳大学达成战略合作，共同建立无人机研发实验室，致力于推动无人机技术的创新和应用。双方将在人才培养、技术研发和产业转化等方面开展深入合作。',
            bottomContent: '这一合作将为无人机行业培养更多专业人才。',
            bottomImages: ['https://via.placeholder.com/150/24f355/FFFFFF?text=Cooperation'],
            publishDate: '2023-10-20T11:30:45',
            status: 'published',
            importantLevel: 'medium',
            publisher: 'admin',
            images: ['https://via.placeholder.com/150/24f355', 'https://via.placeholder.com/150/24f355/000000?text=University+Cooperation']
          }
        ];
        this.saveToStorage();
      }
    } catch (error) {
      console.error('Failed to load news from localStorage:', error);
      this.news = [];
    }
  }

  // 加载新闻数据
  async loadNews() {
    try {
      this.isLoading = true;
      
      // 这里可以添加从API获取数据的代码
      // 模拟API请求延迟
      await new Promise(resolve => setTimeout(resolve, 300));
      
      // 数据已从localStorage加载，这里只需要通知监听器
      this.notifyListeners();
      return true;
    } catch (error) {
      console.error('Failed to load news:', error);
      return false;
    } finally {
      this.isLoading = false;
    }
  }

  // 获取所有新闻
  getAllNews() {
    return [...this.news];
  }

  // 根据ID获取新闻
  getNewsById(id) {
    return this.news.find(news => news.id === id);
  }

  // 获取已发布的新闻
  getPublishedNews() {
    return this.news.filter(news => news.status === 'published');
  }

  // 获取草稿新闻
  getDraftNews() {
    return this.news.filter(news => news.status === 'draft');
  }

  // 添加新闻
  async addNews(newsData) {
    try {
      // 模拟API请求延迟
      await new Promise(resolve => setTimeout(resolve, 300));
      
      const newId = Math.max(...this.news.map(n => n.id), 0) + 1;
      const newNews = {
        ...newsData,
        id: newId,
        // 设置默认值
        bottomContent: newsData.bottomContent || '',
        bottomImages: newsData.bottomImages || [],
        importantLevel: newsData.importantLevel || 'low',
        // 如果没有提供发布人，使用当前登录用户（这里使用模拟数据）
        publisher: newsData.publisher || 'admin'
      };
      
      this.news.push(newNews);
      this.saveToStorage();
      this.notifyListeners();
      
      return newNews;
    } catch (error) {
      console.error('Failed to add news:', error);
      return null;
    }
  }

  // 更新新闻
  async updateNews(id, newsData) {
    try {
      // 模拟API请求延迟
      await new Promise(resolve => setTimeout(resolve, 300));
      
      const index = this.news.findIndex(news => news.id === id);
      if (index === -1) {
        return false;
      }
      
      this.news[index] = {
        ...this.news[index],
        ...newsData
      };
      
      this.saveToStorage();
      this.notifyListeners();
      
      return true;
    } catch (error) {
      console.error('Failed to update news:', error);
      return false;
    }
  }

  // 删除新闻
  async deleteNews(id) {
    try {
      // 模拟API请求延迟
      await new Promise(resolve => setTimeout(resolve, 300));
      
      const initialLength = this.news.length;
      this.news = this.news.filter(news => news.id !== id);
      
      // 如果有新闻被删除
      if (this.news.length !== initialLength) {
        this.saveToStorage();
        this.notifyListeners();
        return true;
      }
      
      return false;
    } catch (error) {
      console.error('Failed to delete news:', error);
      return false;
    }
  }

  // 搜索新闻
  searchNews(query) {
    if (!query) {
      return this.getAllNews();
    }
    
    const searchTerm = query.toLowerCase();
    return this.news.filter(news => 
      news.title.toLowerCase().includes(searchTerm) ||
      news.content.toLowerCase().includes(searchTerm)
    );
  }

  // 上传图片
  async uploadImage(file) {
    try {
      // 模拟图片上传
      return new Promise((resolve) => {
        setTimeout(() => {
          // 使用FileReader读取文件并转换为DataURL作为模拟的上传结果
          const reader = new FileReader();
          reader.onload = (e) => {
            resolve(e.target.result);
          };
          reader.readAsDataURL(file);
        }, 500);
      });
    } catch (error) {
      console.error('Failed to upload image:', error);
      throw error;
    }
  }

  // 获取新闻统计数据
  getNewsStats() {
    const total = this.news.length;
    const published = this.news.filter(n => n.status === 'published').length;
    const draft = this.news.filter(n => n.status === 'draft').length;
    const latest = this.news.sort((a, b) => new Date(b.publishDate) - new Date(a.publishDate))[0];
    
    return {
      total,
      published,
      draft,
      latest
    };
  }

  // 获取当前登录用户（模拟实现）
  getCurrentUser() {
    // 实际应用中应从认证系统获取
    // 这里返回模拟数据
    return {
      username: 'admin',
      role: 'admin'
    };
  }
}

// 导出单例实例
const newsStore = new NewsStore();
export default newsStore;